<template>
<div>
    <Card class="ivu-mb-16" v-width="250">
        <div class="imageurl" @click="changeClick">
            <img :src= datas.path class="canvasImg" />
            <span class="showtype">{{datas.extension}}</span>

            <div class="baseimg" v-if="datas.linkUrl!=='javascript:;'">
                <a target="_self" href="javascript:;" :thislink='datas.linkUrl'><img :ref="`jsImg-${datas.id}`" :src="datas.paths"  class="jsImg"  /></a>
            </div>
            <div class="baseimg" v-else>
              <img :ref="`jsImg-${datas.id}`" :src="datas.paths"  class="jsImg"  />
            </div>
        </div>
        <Row type="flex" align="middle" justify="space-between" class="ivu-mt-8">
            <Col>{{datas.width}}*{{datas.height}}</Col>
            <Col><Icon type="ios-eye-outline" />{{datas.click}}</Col>
            <Col>
                <Select v-model="datas.linkUrl" v-width="80"  >
                    <Option v-for="(it,idx) in datas.selectList" :key="idx" :value="it.value" >{{it.label}}</Option>
                </Select>
            </Col>
        </Row>
        <div v-if="bool">
            <Row type="flex" align="middle" justify="space-between" class="ivu-mt-8">
                <Col><Button size="small" class="realdel" @click="changerealdel(datas)" v-hasC="{name: '-v1-material-img-img-completely-del',flag: '/v1/material/img/img-completely-del'}" ><b>彻底删除</b></Button></Col>
                <Col><Button size="small" class="reduction" @click="changereduction(datas)"  v-hasC="{name: '-v1-material-img-img-reduction',flag: '/v1/material/img/img-reduction'}"><b>还原图片</b></Button></Col>
            </Row>
        </div>
        <div v-else>
            <Row type="flex" align="middle" justify="space-between" class="ivu-mt-8">
                <Col><Button size="small" @click="changedel(datas)" v-hasC="{name: '-v1-material-img-img-del',flag: '/v1/material/img/img-del'}">删除</Button></Col>
                <Col><Button size="small" @click="changetype(datas)" v-hasC="{name: '-v1-material-img-cates-change',flag: '/v1/material/img/cates-change'}">变更类别</Button></Col>
                <Col><Button size="small" @click="changeImg(datas)" v-hasC="{name: '-v1-material-img-img-change',flag: '/v1/material/img/img-change'}">图片替换</Button></Col>
            </Row>
            <div class="boxFotter">
                <span>标签：</span>
                <Input v-model="datas.remarks" placeholder="请输入标签" v-width="173"  @on-blur="changeMark(datas)"/>
            </div>
        </div>
    </Card>

    <!-- 更改图片类型 -->
    <Modal v-model="modalstatus" title="更改当前图类别" width="500">
        <Form ref='changetype' :model='modalForm' :rules="rules">
            <FormItem >
            <Select v-model="modalForm.tagIds" style="width:400px" placeholder="请选择上传类别" filterable multiple>
                <Option v-for="item in typeList" :value="item.id" :key="item.id">
                    {{ item.name }}
                </Option>
            </Select>
            </FormItem>
        </Form>
        <div slot='footer' class="footer">
            <Button  type='primary' :loading="subloading" @click="submitedit('changetype')">保存</Button>
        </div>
    </Modal>
    <!-- 图片替换 -->
    <Modal v-model="imgstatus" title="更改当前图片" width="500">
        <Upload
            ref='upload'
            :format="['jpg','png','gif']"
            :action="requestAction"
            :headers="{'Authorization': 'Bearer ' + token,'projectid':project}"
            :on-success="(res) => upSuccess(res)"
            :show-upload-list="false"
            type="drag"
            >
            <div style="padding: 20px 0" v-if="!imgurl">
                <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                <p>点击上传图片</p>
            </div>
            <div v-else>
            <img :src="imgurl" width="100%" height="350px">
            </div>
        </Upload>
        <div slot='footer' class="footer">
                <Button  type='primary' :loading="imageing" @click='saveImg'>保存</Button>
        </div>
    </Modal>
</div>
</template>

<script>
    import {
        materialimgtagsadd,
        materialimgimgdel,
        materialimgcateschange,
        materialimgimgchange,
        materialimgclickadd,
        materialimgimgcompletelydel,
        materialimgimgreduction
    } from '@/api/sourcematerial.js'
    import Setting from '@/setting';
    import util from '@/libs/util';
    export default {
        name: 'Cardimage',
        props: {
            index: { type: [String, Number] },
            data: { type: Object },
            bool: { type: Boolean, default: false },
            typeList: { type: Array }
        },
        data () {
            return {
                project: util.storage.get('currentProject'),
                token: util.cookies.get('token'),
                datas: {},
                modalstatus: false,
                modalForm: { id: '', tagIds: [] },
                rules: {
                    tagIds: [{ required: true, message: '请选择更改的类别', trigger: 'change' }]
                },
                subloading: false,
                imgstatus: false,
                requestAction: '',
                baseUrl: Setting.apiBaseURL,
                imgurl: '',
                imageing: false
            };
        },

        mounted () {
            this.requestAction = this.baseUrl + `/v1/material/upload/imgs-upload`;
            this.modalForm.id = this.data.id
            this.datas = { ...this.data, show: false, selectList: [{ value: '/swt/', label: '快商通' }, { value: '/tell/', label: '电话' }, { value: 'javascript:;', label: '其他' }] }
            this.datas.paths = this.data.path
            this.datas.path = this.data.path
        },
        beforeDestroy () {
            let img = this.$refs[`jsImg-${this.datas.id}`]
            img.remove()
        },
        methods: {
            // 删除图片
            changedel (item) {
                this.$Modal.confirm({
                    title: '确定将当前图片删除移入回收站？',
                    onOk: () => {
                        materialimgimgdel({ id: item.id }).then(res => {
                            this.$Message.info('删除成功');
                            this.$emit('imgdel', this.index);
                        })
                    }
                })
            },
            // 图片更换
            changeImg () {
                this.imgstatus = true
                this.imgurl = ''
                this.imgPath = ''
            },
            // 切换类型
            changetype () {
                this.modalstatus = true
                this.modalForm.tagIds = []
            },
            // 打标签
            changeMark (item) {
                let params = {
                    id: item.id,
                    remark: item.remarks
                }
                materialimgtagsadd(params).then(res => {
                    this.$Message.success('标记成功');
                })
            },
            // 类别确定
            submitedit (modalForm) {
                this.$refs[modalForm].validate((valid) => {
                    if (valid) {
                        this.subloading = true;
                        let params = {
                            id: this.modalForm.id,
                            tagIds: this.modalForm.tagIds.join(',')
                        }
                        materialimgcateschange(params).then(res => {
                            this.$Message.success('更改成功');
                            this.modalstatus = false;
                            this.subloading = false;
                            this._getimgList()
                        }).catch(() => {
                            this.modalstatus = false;
                            this.subloading = false;
                        })
                    } else {
                        this.$Message.error('请完善表格。');
                    }
                })
            },
            upSuccess (response) {
                let url = response.data.map(item => item.img_url)
                this.imgPath = url
                this.imgurl = `${this.baseUrl}/library_image_tmp${url}`
            },
            saveImg () {
                if (this.imgurl) {
                    this.imageing = true;
                    let params = {
                        id: this.datas.id,
                        imgPath: this.imgPath.join('')
                    }
                    materialimgimgchange(params).then(res => {
                        this.datas.path = this.imgurl
                        this.$Message.success('更改成功');
                        this.imgstatus = false;
                        this.imageing = false;
                    }).catch(() => {
                        this.imgstatus = false;
                        this.imageing = false;
                    })
                } else {
                    this.$Message.error('请选择图片')
                }
            },
            changeClick () {
                //   this.$Copy({text:`<a target="_self" href="" thislink='${this.datas.linkUrl}'><img  src="${this.datas.paths}"  class="jsImg" /></a>`})
                materialimgclickadd({ id: this.datas.id })
                // 复制图片
                let img = this.$refs[`jsImg-${this.datas.id}`]
                console.log(this.$refs[`jsImg-${this.datas.id}`])
                var selection = window.getSelection();
                var range = document.createRange();
                this.log(this.datas.linkUrl,'this.datas.linkUrl')
                range.selectNode(img);
                selection.removeAllRanges();
                selection.addRange(range);
                document.execCommand('copy');
                if (document.execCommand('copy')) {
                    this.$Notice.success({
                        title: '温馨提示：',
                        desc: '复制当前图片已成功'
                    });
                }
            },
            // 彻底删除图片
            changerealdel (item) {
                this.$Modal.confirm({
                    title: '彻底删除该图片，将无法恢复！如果该图片外部站点有引用，将导致外网图片无法访问。',
                    onOk: () => {
                        let params = {
                            id: item.id,
                            type: 1
                        }
                        materialimgimgcompletelydel(params).then(res => {
                            this.$Message.info('删除成功');
                            this.$emit('imgdel', this.index);
                        })
                    }
                })
            },
            // 还原视频或者图片
            changereduction (item) {
                this.$Modal.confirm({
                    title: '是否还原该图片?',
                    onOk: () => {
                        let params = {
                            id: item.id,
                            type: 1
                        }
                        materialimgimgreduction(params).then(res => {
                            this.$Message.info('还原成功');
                            this.$emit('imgdel', this.index);
                        })
                    }
                })
            }
        }
    };
</script>

<style lang="less" scoped>
.imageurl{
    width: 100%;
    height: 250px;
    position: relative;
    .canvasImg{
        width: 100%;
        height: 100%;
        object-fit: contain;
    }
    .showtype{
        position: absolute;
        right: 10px;
        top: 10px;
        padding: 0px 20px;
        border-radius: 5px;
        background: #515a6e;
        font-size: 16px;
        opacity: .5;
        color: #fff;
        display: none;
    }
    &:hover{
        .showtype{
            display: block;
        }
    }
   .baseimg{
        position: fixed;
        z-index:-888;
        top:0;
        overflow: hidden;
        opacity: 0;
    }
}
.boxFotter{
    padding:8px 0 0 0;
}
</style>
